package com.zsh.wx_account1.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Author ZhaoShuHao
 * @Date 2023/8/22 16:36
 */
public class WordUtil {
    //聚合数据网站的api接口（同义词/反义词查询）
    public static final String WORD_URL = "http://apis.juhe.cn/tyfy/query?key=%s";
    //申请接⼝的请求key
    // TODO: 您需要改为⾃⼰的请求key
    public static final String KEY = "fe4c67727c5cc2cbc12094a563c44305";
    public static String getWords(String word) {
        HttpUtil httpUtil = new HttpUtil();
        //发送http请求的url
        String url = String.format(WORD_URL, KEY);
        final String response =httpUtil.doPost(url,"word="+word,"application/x-www-form-urlencoded");
        System.out.println("接⼝返回：" + response);
        try {
            JSONObject jsonObject =
                    JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调⽤接⼝成功");
                JSONObject result =
                        jsonObject.getJSONObject("result");
                JSONArray words = result.getJSONArray("words");
                StringBuilder stringBuilder = new
                        StringBuilder();
                words.stream().forEach(w->stringBuilder.append(w+" "));
                System.out.println(stringBuilder);
                return "'"+word+"'的同义词有："+stringBuilder.toString();
            } else {
                System.out.println("调⽤接⼝失败：" +
                        jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "'"+word+"'的同义词暂没找到，请联系管理员扩展";
    }

}
